<template>
    <view class="">
        <view class="column1">
            <view class="title">无忧心理助手</view>
            <view class="btn">
                <view class="icn" :class="{on:mute}" @click="changeMute()"></view>
                <view class="icn" @click="changeNext()">
                    <view class="con" v-if="next">
                        <view @click="clear()">清除上下文</view>
                        <!-- <view @click.stop="openCz()">问答充值（10）</view> -->
                    </view>
                </view>
            </view>
        </view>
        <scroll-view class="scroll-view" :style="{height:conH + 'px'}" :scroll-y="true" :scroll-top="scrollTop"
            :scroll-with-animation="false">
            <view class="content" id="scroll-view-content" @click="removeCz()">
                <view class="column2">
                    <view v-for="(item,index) in indexData" :key="index" :class="item.role=='user'?'right':'left'">
                        <view class="text" v-if="item.role=='user'" style="white-space:pre-wrap;">
                            <u-loading mode="circle" color='#fff' :show="item.content=='al!@'"></u-loading>
                            <view v-if="item.content!='al!@'" style="text-align: left;">{{item.content}}</view>
                        </view>
                        <view class="text" v-else>
                            <u-loading mode="circle" color='#0074ff' :show="item.content.length==0"></u-loading>
                            <view class="con" style="white-space:pre-wrap;">
                                {{item.content}}
                            </view>
                            <view class="bot" v-if="!item.btn && index==indexData.length-1">
                                <view class="fl" v-if="item.show">
                                    <view @click="copyText(item.content)"></view>
                                </view>
                                <view class="fr">
                                    <view class="stop" v-if="item.agian" :class="{on:item.stop}" @click="stop()"></view>
                                    <view class="agion" v-else @click="agion(index)"></view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <view class="chongZ" :class="{on:czActive}" @click.stop="maopao()">
                    <view class="title">充值</view>
                    <view class="num">余额：10次</view>
                    <view class="list">
                        <view class="dd on">
                            <view class="con">
                                <view><text>5</text>次</view>
                                <view>1元</view>
                            </view>
                        </view>
                        <view class="dd">
                            <view class="con">
                                <view><text>5</text>次</view>
                                <view>1元</view>
                            </view>
                        </view>
                        <view class="dd">
                            <view class="con">
                                <view><text>5</text>次</view>
                                <view>1元</view>
                            </view>
                        </view>
                        <view class="dd">
                            <view class="con">
                                <view><text>5</text>次</view>
                                <view>1元</view>
                            </view>
                        </view>
                        <view class="dd">
                            <view class="con">
                                <view><text>5</text>次</view>
                                <view>1元</view>
                            </view>
                        </view>
                        <view class="dd">
                            <view class="con">
                                <view><text>5</text>次</view>
                                <view>1元</view>
                            </view>
                        </view>
                    </view>
                    <view class="btn">立即充值1元</view>
                    <view class="text">充值代表已阅读并同意<text>《用户充值协议》</text></view>
                </view>
            </view>
        </scroll-view>
        <view class="footer" :style="{bottom: inputTop + 'px'}">
            <view class="yy" :class="{on:active}" v-if="show">
                <view class="btn" @click="changeShow"></view>
                <view class="an" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
                    {{disabled?'回答中..':'按住说话'}}
                </view>
                <view class="bg">
                    <view class="title">{{content?content:'我在听，请说话'}}</view>
                    <view class="titlec">松开发送 上滑取消</view>
                </view>
            </view>
            <view class="jp" v-else>
                <view class="btn" @click="changeShow"></view>
                <input type="text" :disabled='disabled' confirm-type="send" :adjust-position="false" @confirm="submit()"
                    v-model="content" :placeholder="disabled?'回答中..':'请输入..'" />
            </view>
        </view>
		<u-modal v-model="showModal" title="登录提醒"  confirm-text="立即登录" @confirm="toLogin" content="该功能需要用户登录,请您先登录!"></u-modal>
    </view>
</template>

<script>
    var AVAudioSession = plus.ios.importClass("AVAudioSession");
    var AVSpeechSynthesizer = plus.ios.importClass("AVSpeechSynthesizer");
    var AVSpeechUtterance = plus.ios.importClass("AVSpeechUtterance");
    var AVSpeechSynthesisVoice = plus.ios.importClass("AVSpeechSynthesisVoice");
    var sppech
    var voice
    export default {
        data() {
            return {
                next: false,
                mute: false,
                indexData: [],
                show: false,
                active: false,
                on: false,
                isSwipeUp: false,
                startY: 0,
                timer: null,
                content: null,
                textBox: null,
                textNum: 0,
                disabled: false,
                czActive: false,
                inputTop: 10,
                token: null,
                vh: null,
                conH: null,
                scrollTop: 0,
                audio: null,
                videoContext: null,
                myPhone: null,
				showModal:false,
				isLogin:false
            };
        },
        
        onLoad() {
			var _this = this
			if(!uni.$_getToken()){
				this.showModal = true
				return
			}else{
				this.isLogin = true
				uni.$_addAccess(this)
			}
            
            uni.getSystemInfo({
                success: function(info) {
                    _this.vh = info.windowHeight
                    _this.info = info.platform
                    _this.conH = _this.vh - 200
                    if (_this.info === 'ios') {
                        sppech = new AVSpeechSynthesizer();
                        voice = AVSpeechSynthesisVoice.voiceWithLanguage("zh-CN")
                    }

                }
            });

            uni.onKeyboardHeightChange(this.onKeyboardHeightChange);
            plus.speech.addEventListener('recognizing', ({
                partialResult
            }) => {
                this.content = partialResult
                console.log(partialResult)
            }, false);
        },
		onShow() {
			
			
		},
		onReady() {
			var _this = this
			uni.$_post({
			    url: "ai-index",
			    that: _this,
			    params: [],
			    success(res) {
			        if (res.code == 0) {
			            _this.textBox = res.data
			            var data = res.data
			            if (!_this.mute) {
			
			                _this.speak(data)
			            }
			            var str = _this.indexData
			            let b = {
			                content: '',
			                role: "assistant",
			                btn: true
			            }
			            str.push(b)
			            //声明一个变量，用来监听要分割的长度
			            _this.textNum = 0
			            _this.timer = setInterval(() => {
			                b.content = data.substr(0, _this.textNum);
			                if (_this.textNum < data.length) {
			                    _this.textNum++
			                } else {
			
			                    clearInterval(_this.timer);
			                }
			            }, 100);
			        }
			    },
			    fail(err) {
			        console.log(err)
			    }
			});
		},
        onUnload() {
            uni.offKeyboardHeightChange(this.onKeyboardHeightChange);

        },
        onBackPress() {
            clearInterval(this.timer);
        },
        onHide() {
            this.stopSpeak()
        },
        methods: {
			toLogin(){
				uni.reLaunch({
					url:'/pages/login/login?pathType=3'
				})
			},
            scrollToBottom() {
                var _this = this
                uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((res) => {
                    let top = res.height - _this.conH;
                    if (top > 0) {
                        this.scrollTop = top;
                    }
                }).exec()
            },
            onKeyboardHeightChange(res) {
                const {
                    height,
                    duration
                } = res;
                // 键盘弹起
                if (height > 0) {
                    const keyboardHeight = height; // 键盘的高度
                    this.inputTop = this.info == 'ios' ? keyboardHeight - 80 : keyboardHeight - 50;

                    this.conH = this.vh - keyboardHeight - 130
                }
                // 键盘收回
                else {
                    this.inputTop = 10;
                    this.conH = this.vh - 200
                }
                this.scrollToBottom()
            },
            maopao() {},
            goTo(url) {
                uni.$_navFn('to', url)
            },
            removeCz() {
                this.czActive = false
            },
            openCz() {
                this.czActive = true
                this.changeNext()
            },
            changeShow() {
				if(this.disabled){
					return
				}
                this.show = !this.show
                this.content = null
            },
            changeNext() {
                this.next = !this.next
            },
            changeMute() {
                this.mute = !this.mute
                if (!this.mute) {
                    if (this.info === 'android') {
                        // this.speak()
                    } else {
                        sppech.continueSpeaking(90);
                    }
                } else {
                    this.stopSpeak()
                }
            },
            submit() {
                let that = this;
                if (!that.content && that.show) {
                    uni.showToast({
                        title: '语音识别失败,请重试',
                        icon: 'none',
                        duration: 1500
                    })
                    that.indexData = that.indexData.slice(0, -1)
					this.disabled = false
                    return

                }
                if (!that.content) {
                    return
                }
                
                that.disabled = true
                let str = that.indexData
                if (!that.show) {
                    let a = {
                        content: that.content,
                        role: "user"
                    }
                    str.push(a)

                } else {
                    that.indexData[that.indexData.length - 1].content = that.content
                }
                let b = {
                    content: '',
                    role: "assistant",
                    agian: true,
                    show: false,
                    stop: false
                }
                str.push(b)
                setTimeout(() => {
                    that.scrollToBottom()
                }, 100)
                that.content = null
                uni.$_post({
                    url: "ai-index",
                    that: that,
                    params: str,
                    success(res) {
                        if (res.code == 0) {
                            var data = res.data
                            that.stopSpeak()
                            that.textBox = res.data
                            that.scrollToBottom()
                            //声明一个变量，用来监听要分割的长度
                            that.textNum = 0
                            that.speak(res.data)
                            that.timer = setInterval(() => {
                                that.scrollToBottom()
                                //取到data.content的第wenlen位
                                b.content = data.substr(0, that.textNum);
                                //wenlen大于data.content的长度，停止计时器
                                if (that.textNum < data.length) {
                                    that.textNum++
                                    
                                } else {
                                    that.disabled = false
                                    b.agian = false
                                    b.show = true
                                    clearInterval(that.timer);
                                }
                            }, 100);
                        }
                    },
                    fail(err) {
                        console.log(err)
                    }
                });
            },
            stop() {
                if (this.info === 'android') {
                    this.stopSpeak()
                } else {
                    sppech.pauseSpeakingAtBoundary(90);
                }

                if (this.indexData[this.indexData.length - 1].stop) {
                    this.disabled = true
                    var data = this.textBox
                    if (this.info === 'android') {
                        this.speak(data.slice(this.textNum))
                    } else {
                        sppech.continueSpeaking(90);
                    }

                    this.timer = setInterval(() => {
                        this.scrollToBottom()
                        //取到data.content的第wenlen位
                        this.indexData[this.indexData.length - 1].content = data.substr(0, this.textNum);
                        //wenlen大于data.content的长度，停止计时器
                        if (this.textNum < data.length) {
                            this.textNum++
                        } else {
                            this.indexData[this.indexData.length - 1].agian = false
                            this.indexData[this.indexData.length - 1].show = true
                            clearInterval(this.timer);
                            this.disabled = false
                        }
                    }, 100);
                } else {
                    clearInterval(this.timer);
                    this.disabled = false
                }
                this.indexData[this.indexData.length - 1].stop = !this.indexData[this.indexData.length - 1].stop
            },
            agion(index) {
                this.stopSpeak()
                let array = this.indexData;
                
                let indexToRemoveFrom = index-1; // 假设我们想移除下标2之后的所有元素
                if(this.show){
                    indexToRemoveFrom = index
                }
                // 使用splice从下标2开始移除到数组末尾所有元素
                this.content = this.indexData[index-1].content
                array.splice(indexToRemoveFrom, array.length - indexToRemoveFrom);
                
                this.submit()
            },
            handleTouchStart(event) {
                if (this.disabled) {
                    return
                }
				this.stopSpeak()
                // this.stopSpeak()
                this.startY = event.touches[0].pageY - 50;
                this.active = true
                this.startRecognize()
            },
            handleTouchMove(event) {
                if (this.disabled) {
                    return
                }
                const moveY = event.touches[0].pageY;
                if (moveY < this.startY) {
                    this.isSwipeUp = true;
                } else {
                    this.isSwipeUp = false;
                }
            },
            handleTouchEnd(event) {
                if (this.disabled) {
                    return
                }
				this.disabled = true
                if (this.isSwipeUp) {
                    this.content = null
                    plus.speech.stopRecognize();
                    this.disabled = false
                } else {
                    let str = this.indexData
                    let a = {
                        content: "al!@",
                        role: "user"
                    }
                    str.push(a)
                    setTimeout(()=>{
                        plus.speech.stopRecognize();
                        this.submit()
                    },3000)
                }
                this.startY = 0;
                this.isSwipeUp = false;
                this.active = false
            },
            startRecognize() {
                var options = {
                    engine: 'baidu',
                    userInterface: false
                };
                let _this = this;
                var text = ''
                plus.speech.startRecognize(options, function(s) {
                    _this.content=s
                }, function(e) {
                    uni.showToast({
                        title: '语音识别失败,请重试',
                        icon: 'none',
                        duration: 1500
                    })
                    that.indexData = that.indexData.slice(0, -1)
                    this.disabled = false
                });
            },
            copyText(text) {
                uni.setClipboardData({
                    data: text,
                    success: function() {
                        // 可以添加用户友好的提示，例如使用uni.showToast提示复制成功
                        uni.$u.toast('复制成功')
                    }
                });
            },
            changeEnCode(str) {
                let res = []
                for (let i = 0; i < str.length; i++) {
                    // 这个不是正常的encodeUnicode 颠倒了大小端的位置  
                    res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-2) + ("00" + str.charCodeAt(i).toString(16))
                        .slice(-
                            4, -2)
                }
                let strCode = "\\u" + res.join("\\u")
                strCode = strCode.replace(/\\/g, "%")
                return unescape(strCode)
            },
            AndriodSpeechToVoice(text) {
                uni.requireNativePlugin('Ba-TTS').speak({
                        text: text, //文本； 注意：如果是数字单读（如叫号1001），可用空格隔开，如“1 0 0 1”）
                        pitch: 1.3, // 设置音调，值越大声音越尖（女生），值越小则变成男声,默认是1
                        //speed: 1 //设定语速 ，默认1正常语速
                    },
                    (res) => {
                        
                    });
                if (this.mute) {
                    this.stopSpeak()
                }
            },
            iosSpeechToVoice(text) {
                AVAudioSession.sharedInstance().setCategoryerror("AVAudioSessionCategoryPlayback", null);
                var utterance = AVSpeechUtterance.speechUtteranceWithString(text);

                utterance.plusSetAttribute("volume", 1);

                sppech.speakUtterance(utterance);
                if (this.mute) {
                    this.stopSpeak()
                }
            },
            speak(text) {
                var _this = this
				if (this.info === 'android') {
				    _this.AndriodSpeechToVoice(text);
				} else {
				    _this.iosSpeechToVoice(text)
				}
            },
            stopSpeak() { //停止播放
                if (this.info === 'android') {
                    uni.requireNativePlugin('Ba-TTS').stopSpeak(
                        (res) => {
                            
                        });
                } else {
                    sppech.stopSpeakingAtBoundary(0)
                }


            },
            clear() {
                this.indexData = []
            }
        }
    }
</script>

<style lang="scss">
    .column1 {
        margin-bottom: 40rpx;
        position: sticky;
        top: 0;
        width: 100%;
        padding: 120rpx 30rpx 40rpx;
        z-index: 3;
        background: #fff url(@/static/img/index/indexTop2.png) no-repeat top center / 100% auto;
        display: flex;
        justify-content: space-between;

        .title {
            font-size: 60rpx;
            font-weight: bold;
            color: #191919;
            line-height: 62rpx;
        }

        .btn {
            display: flex;
            justify-content: space-between;
            margin-top: 10rpx;

            .icn {
                width: 42rpx;
                margin-left: 40rpx;
                height: 42rpx;
                background: url("/static/img/interact/sy.png") no-repeat center / 42rpx;
                position: relative;
            }

            .icn:nth-child(1).on {
                background: url("/static/img/interact/jy.png") no-repeat center / 42rpx;
            }

            .icn:nth-child(2) {
                background: url("/static/img/interact/more.png") no-repeat center / 30rpx;
                position: relative;

                .con {
                    position: absolute;
                    right: 24rpx;
                    top: 65rpx;
                    width: 318rpx;
                    height: 240rpx;
                    background: #fff;
                    z-index: 2;
                    border-radius: 24rpx;
                    box-shadow: 0px 0px 20rpx 0px rgba(0, 0, 0, 0.2);
                    box-sizing: border-box;
                    padding: 56rpx 0 0 45rpx;

                    view {
                        font-size: 30rpx;
                        font-weight: bold;
                        line-height: 32rpx;
                        padding-left: 45rpx;
                        margin-bottom: 70rpx;
                        background: url("/static/img/interact/qc.png") no-repeat center left / 26rpx;
                    }

                    view:nth-child(2) {
                        background: url("/static/img/interact/cz.png") no-repeat center left / 30rpx;
                    }
                }
            }
        }
    }

    .content {
        display: block;
        width: 100%;
        padding: 0 30rpx;
        background: #fff;
        box-sizing: border-box;
        overflow-y: auto;
        margin-bottom: 200px;
        width: 100%;

        .column2 {
            overflow: hidden;

            .right {
                max-width: calc(100% - 40rpx);
                margin-left: auto;
                text-align: right;
                margin-bottom: 20rpx;

                .text {
                    background: #0074ff;
                    font-size: 32rpx;
                    line-height: 40rpx;
                    border-radius: 35rpx;
                    color: #fff;
                    padding: 23rpx 30rpx;
                    display: inline-block;
                }
            }

            .left {
                max-width: calc(100% - 40rpx);
                margin-right: auto;
                text-align: left;
                margin-bottom: 20rpx;

                .text {
                    background: #f7f7f7;
                    min-width: 50%;
                    border-radius: 35rpx;
                    padding: 23rpx 30rpx;
                    display: inline-block;

                    .con {
                        color: #000000;
                        font-size: 32rpx;
                        line-height: 40rpx;
                    }

                    .bot {
                        border-top: 1rpx solid #e9e9e9;
                        margin-top: 23rpx;
                        padding-top: 23rpx;
                        overflow: hidden;

                        .fl {
                            view {
                                display: inline-block;
                                width: 70rpx;
                                height: 70rpx;
                                border-radius: 35rpx;
                                margin-right: 17rpx;
                                background: url("/static/img/interact/fz.jpg") no-repeat center / 100%;
                            }

                            view:nth-child(2) {
                                background-image: url("/static/img/interact/bb.jpg");
                            }

                            view:nth-child(2).on {
                                background-image: url("/static/img/interact/bbt.png");
                            }
                        }

                        .fr {
                            view {
                                display: inline-block;
                                width: 70rpx;
                                height: 70rpx;
                                border-radius: 35rpx;
                                margin-left: 17rpx;
                            }

                            view.stop {
                                background: url("/static/img/interact/stopon.png") no-repeat center / 100%;
                            }

                            view.stop.on {
                                background: url("/static/img/interact/stop.png") no-repeat center / 100%;
                            }

                            view.agion {
                                background: url("/static/img/interact/cx.jpg") no-repeat center / 100%;
                            }
                        }
                    }
                }
            }
        }

        .column3 {
            padding-bottom: 210rpx;

            .info {
                margin-bottom: 20rpx;
                width: calc(100% - 40rpx);

                view {
                    border: 1rpx solid #e6e6e6;
                    padding: 17rpx 20rpx;
                    border-radius: 35rpx;
                    font-size: 26rpx;
                    color: #050505;
                    line-height: 32rpx;
                    display: inline-block;
                    font-weight: bold;
                }
            }
        }

        .chongZ {
            position: fixed;
            left: 30rpx;
            right: 30rpx;
            bottom: 150rpx;
            background: #fff;
            padding: 50rpx 30rpx 40rpx;
            border-radius: 30rpx;
            box-shadow: 0px 0px 30rpx 0px rgba(0, 0, 0, 0.2);
            z-index: 10;
            transform: translateY(150%);
            text-align: center;
            transition: all .4s ease;

            .title {
                font-size: 32rpx;
                font-weight: bold;
                line-height: 34rpx;
                color: #111111;
                margin-bottom: 60rpx;
            }

            .num {
                position: absolute;
                right: 30rpx;
                top: 50rpx;
                line-height: 34rpx;
                font-size: 24rpx;
                color: #7e7f85;
            }

            .list {
                margin-right: -15rpx;
                overflow: hidden;
                margin-bottom: 15rpx;

                .dd {
                    width: 33.3333%;
                    float: left;
                    display: inline;
                    margin-bottom: 20rpx;

                    .con {
                        margin-right: 15rpx;
                        background: #f8f8f8;
                        height: 135rpx;
                        box-sizing: border-box;
                        padding-top: 35rpx;
                        border-radius: 10rpx;

                        view:nth-child(1) {
                            font-size: 24rpx;
                            font-weight: bold;
                            color: #111111;
                            line-height: 24rpx;
                            margin-bottom: 18rpx;

                            text {
                                font-size: 36rpx;
                            }
                        }

                        view:nth-child(2) {
                            font-size: 24rpx;
                            color: #888888;
                            line-height: 26rpx;
                        }
                    }
                }

                .dd.on {
                    .con {
                        background: #0074ff;

                        view:nth-child(1) {
                            color: #fff;
                        }

                        view:nth-child(2) {
                            color: #fff;
                        }
                    }
                }
            }

            .btn {
                width: 90%;
                margin: 0 auto;
                margin-bottom: 20rpx;
                border-radius: 30px;
                height: 85rpx;
                line-height: 85rpx;
                background: #5a64c5;
                font-size: 30rpx;
                color: #ffffff;
            }

            .text {
                font-size: 21rpx;
                color: #7e7f85;
                line-height: 23rpx;

                text {
                    color: #5a64c5;
                }
            }
        }

        .chongZ.on {
            transform: translateY(0);
        }
    }

    .footer {
        position: fixed;
        left: 30rpx;
        bottom: 10rpx;
        right: 30rpx;
        background: #fff;
        z-index: 10;

        .yy {
            position: relative;
            height: 108rpx;
            box-shadow: 0px 0px 30rpx 0px rgba(0, 0, 0, 0.2);
            border-radius: 30rpx;
            line-height: 108rpx;
            transition: all .4s ease;

            .btn {
                position: absolute;
                right: 0;
                top: 0;
                width: 108rpx;
                height: 108rpx;
                background: url("/static/img/interact/jp.png") no-repeat center / 50rpx;
                transition: all .4s ease;
            }

            .an {
                font-size: 32rpx;
                font-weight: bold;
                text-align: center;
                transition: all .4s ease;
            }

            .bg {
                width: 100vw;
                padding-top: 93.2%;
                background: url("/static/img/interact/shbg.png") no-repeat center top / 100%;
                z-index: 2;
                position: fixed;
                left: 0;
                bottom: 120rpx;
                text-align: center;
                display: none;
                transition: all .4s ease;

                .title {
                    position: absolute;
                    left: 0;
                    bottom: 376rpx;
                    width: 100%;
                    font-size: 40rpx;
                    font-weight: bold;
                    line-height: 42rpx;
                    color: #000000;
                    transition: all .4s ease;
                }

                .titlec {
                    position: absolute;
                    left: 0;
                    bottom: 188rpx;
                    width: 100%;
                    font-size: 27rpx;
                    color: #777777;
                    line-height: 27rpx;
                    transition: all .4s ease;
                }
            }
        }

        .yy.on {
            box-shadow: none;

            .an {
                &::before {
                    display: block;
                    content: "";
                    position: absolute;
                    left: 0;
                    top: 0;
                    bottom: 0;
                    right: 0;
                    background: url("/static/img/interact/sh.png") no-repeat center / 100%;
                    border-radius: 30px;
                    z-index: 3;
                }
            }

            .bg {
                display: block;
            }
        }

        .jp {
            height: 108rpx;
            box-shadow: 0px 0px 30rpx 0px rgba(0, 0, 0, 0.2);
            border-radius: 30rpx;
            line-height: 108rpx;
            overflow: hidden;

            .btn {
                float: right;
                display: inline;
                width: 108rpx;
                height: 108rpx;
                background: url("/static/img/interact/yy.png") no-repeat center / 50rpx;
            }

            input {
                float: left;
                display: inline;
                width: calc(100% - 108rpx);
                box-sizing: border-box;
                height: 108rpx;
                line-height: 108rpx;
                padding-left: 30rpx;
                font-size: 32rpx;
                color: #333;

                &::placeholder {
                    font-size: 32rpx;
                    color: #848484;
                }
            }
        }
    }
</style>